package org.oa.controller.base;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.oa.common.AuthCode;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 验证码处理类
 * @author Administrator
 *
 */
@Controller
public class AuthCodeController {
	public static final String AUTH_CODE = "AUTH_CODE";
	private static final long serialVersionUID = 1L;
	@RequestMapping("verify")
	public void getAuthCode(HttpSession session, HttpServletResponse response) {
		//获取验证码
		String code = AuthCode.getAuthCode();
		//将验证码存储到session中，方便后面的判断
		session.setAttribute(AUTH_CODE,code);
		//获取验证码图片
		BufferedImage img = AuthCode.getCodeImg(code);
		try{
		//输出验证码图片到客户端
		ImageIO.write(img, "JPEG", response.getOutputStream());
		}catch(Exception e){
			//e.printStackTrace();
		}
	}
	
	/**
	 * 获取验证码进行匹配
	 * @param code
	 * @param session
	 * @return
	 */
	@RequestMapping("getVerifyCode")
	@ResponseBody
	public Map getAuthCode(String code,HttpSession session) {
		//获取session中的验证码
		String session_code = (String)session.getAttribute(AUTH_CODE);
		Map map = new HashMap();
		map.put("msg", "验证码正确");
		map.put("flag", 0);
		if(!StringUtils.isEmpty(code)){
			if(!code.equalsIgnoreCase(session_code)){
				map.put("msg", "验证码不正确");
				map.put("flag", 2);
			}
		}else{
			map.put("msg", "请输入验证码");
			map.put("flag", 1);
		}
		
		return map;
	}
}
